/*
 * Copyright 2013-2014 the original author or authors.
 * Licensed under the Apache License, Version 2.0 (the "License");
 * you may not use this file except in compliance with the License.
 * You may obtain a copy of the License at
 *
 *      http://www.apache.org/licenses/LICENSE-2.0
 *
 * Unless required by applicable law or agreed to in writing, software
 * distributed under the License is distributed on an "AS IS" BASIS,
 * WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
 * See the License for the specific language governing permissions and
 * limitations under the License.
 */
package com.xdtech.coder.controller;

import java.io.BufferedInputStream;
import java.io.BufferedOutputStream;
import java.io.File;
import java.io.FileInputStream;
import java.io.IOException;
import java.io.InputStream;
import java.io.OutputStream;
import java.util.ArrayList;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;

import org.apache.commons.io.FileUtils;
import org.apache.commons.lang.StringUtils;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RequestMethod;
import org.springframework.web.bind.annotation.ResponseBody;
import org.springframework.web.servlet.ModelAndView;

import com.xdtech.coder.CodeCreater;
import com.xdtech.coder.model.ModelField;
import com.xdtech.coder.model.ModelTable;
import com.xdtech.coder.service.ModelFieldService;
import com.xdtech.coder.service.ModelTableService;
import com.xdtech.coder.vo.Coder;
import com.xdtech.coder.vo.ModelFieldItem;
import com.xdtech.coder.vo.ModelTableItem;
import com.xdtech.common.utils.JsonUtil;
import com.xdtech.common.utils.ZipUtils;
import com.xdtech.web.model.ResultMessage;

/**
 * 
 * @author max.zheng
 * @create 2014-10-30下午10:22:46
 * @since 1.0
 * @see
 */
@Component
@RequestMapping("/codeCreater.do")
public class CodeCreaterController {
	@Autowired
	private ModelTableService modelTableService;
	@Autowired
	private ModelFieldService modelFieldService;
	
	@RequestMapping(params = "codeCreater")
	public ModelAndView skipCodeCreater() {
		return new ModelAndView("codeCreater/codeCreater_ftl");
	}
	@RequestMapping(params = "createCode")
	@ResponseBody
	public ResultMessage createCode(HttpServletRequest request,String data) {
		Map<String, Class> classMap = new HashMap<String, Class>();
		classMap.put("fields", ModelField.class);
		classMap.put("model", ModelTable.class);
		Coder coder = (Coder) JsonUtil.getObjByJson(data, Coder.class,classMap);
		String folderName = "coder_"+System.currentTimeMillis();
		String fileUrl = request.getRealPath("/")+"/"+folderName;
		CodeCreater.create(coder,fileUrl);
		ResultMessage rs = new ResultMessage();
		rs.setObj(folderName);
		return rs;
	}
	
	@RequestMapping(params = "deleteCode")
	@ResponseBody
	public ResultMessage deleteCode(String ids) {
		ResultMessage r = new ResultMessage();
		if (StringUtils.isNotEmpty(ids)) {
			String[] tempIds = ids.split(",");
			List<Long> idList = new ArrayList<Long>();
			for (String id : tempIds) {
				idList.add(Long.valueOf(id));
			}
			modelTableService.deleteModelTables(idList);
			r.setSuccess(true);
		}else {
			r.setSuccess(false);
		}
		return r;
	}
	
	@RequestMapping(params = "loadModels", method = RequestMethod.POST)
	@ResponseBody
	public Map<String, Object> loadModels() {
		Map<String, Object> results = new HashMap<String, Object>();
		List<ModelTableItem> modelTables = modelTableService.getAllItems();
		results.put("total", modelTables.size());
		results.put("rows", modelTables);
		return results;
	}
	
	@RequestMapping(params = "loadModelFields")
	@ResponseBody
	public List<ModelFieldItem> loadModelFields(Long tableId) {
		List<ModelFieldItem> modelFieldItems = modelFieldService.loadFieldsByTableId(tableId);
		return modelFieldItems;
	}
	@RequestMapping(params="downLoadCode")
	public void downLoadCode(HttpServletRequest request,HttpServletResponse response,String folderName) {
		String fileUrl = request.getRealPath("/")+"/"+folderName;
		try
		{
			response.setCharacterEncoding("UTF-8");
			if (ZipUtils.zip(fileUrl, fileUrl+".zip"))
			{
				//读写压缩好的代码
		        InputStream fis = new BufferedInputStream(new FileInputStream(new File(fileUrl+".zip")));
		        byte[] buffer = new byte[fis.available()];
		        fis.read(buffer);
		        fis.close();
		        
		        response.setHeader("Content-Disposition", "attachment;filename="+folderName+".zip");
		        OutputStream toClient = new BufferedOutputStream(response.getOutputStream());
		        response.setContentType("application/octet-stream");
		        toClient.write(buffer);
		        toClient.flush();
		        toClient.close();
			}else
			{
				
			}
			//判断压缩文件是否存在，存在就删除 
			//重新删除
			FileUtils.deleteDirectory(new File(fileUrl));
			File zipCoder = new File(fileUrl+".zip");
			if (null != zipCoder&&zipCoder.exists())
			{
				zipCoder.delete();
			}
		}
		catch (IOException e)
		{
			e.printStackTrace();
		}
	}
}
